package com.cplatform.movie.back.store.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cplatform.dbhelp.page.Page;
import com.cplatform.movie.back.entity.AuditStep;
import com.cplatform.movie.back.model.SessionUser;
import com.cplatform.movie.back.service.BsFileService;
import com.cplatform.movie.back.store.entity.Store;
import com.cplatform.movie.back.store.service.StoreService;
import com.cplatform.movie.back.sys.entity.SysRegion;
import com.cplatform.movie.back.sys.entity.SysUser;
import com.cplatform.movie.back.sys.service.SysRegionService;
import com.cplatform.movie.back.sys.service.UserService;
import com.cplatform.movie.back.utils.AppConfig;
import com.cplatform.movie.back.utils.JsonRespWrapper;
import com.cplatform.movie.back.utils.LogUtils;
import com.cplatform.movie.back.utils.RegUtils;
import com.cplatform.util2.TimeStamp;

/**
 * Title. 商户管理控制层<br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2015年6月12日 下午2:04:35
 * <p>
 * Author: liuyt
 * <p>
 * Version: 1.0
 * <p>
 */
@Controller
@RequestMapping(value = "/store")
public class StoreController {

	private static final Logger log = Logger.getLogger(StoreController.class);

	@Autowired
	private LogUtils logUtils;

	@Autowired
	private StoreService storeService;

	@Autowired
	private SysRegionService sysRegionService;

	@Autowired
	private SysRegionService sysRegonService;

	@Autowired
	private BsFileService bsFileService;

	@Autowired
	private AppConfig config;

	@Autowired
	private UserService userService;

	/**
	 * 列表显示商户信息
	 * 
	 * @param store
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String storeList(Store store, @RequestParam(value = "page", required = false, defaultValue = "1") int page, Model model) {
		try {
			Page<Store> storeList = storeService.listStore(store, page, Page.DEFAULT_PAGESIZE, null, null);
			model.addAttribute("pageData", storeList);
		} catch (Exception e) {
			log.error("查询商户列表失败", e);
		}
		model.addAttribute("statusMap", Store.statusMap);
		return "store/store-list";
	}

	/**
	 * 进入商户增加页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/storeAdd", method = RequestMethod.GET)
	public String toStoreAddPage(Model model) {
		Store store = new Store();
		model.addAttribute("store", store);
		model.addAttribute("uploadImgId", new Date().getTime());
		model.addAttribute("pid", SessionUser.getSessionUser().getSysUnit().getAreaCode());
		return "store/store-add";
	}

	/**
	 * 完成商户增加
	 * 
	 * @param uploadfile
	 *            合同文件
	 * @param store
	 *            商户
	 * @return
	 */
	@RequestMapping(value = "/storeAdd", method = RequestMethod.POST)
	@ResponseBody
	public Object storeSave(Store store) {
		try {
			boolean exit = storeService.checkExit(store);
			if (!exit) {
				return JsonRespWrapper.successAlert("商户名已经存在!");
			}
			if (!RegUtils.onlyNumAndcCharacterAndAlphabet(store.getName())) {
				return JsonRespWrapper.successAlert("商户名不合法!");
			}

//			store.setSysUserId(SessionUser.getSessionUser().getId());
			store.setCreateTime(TimeStamp.getTime(14));
			store.setStatus(0l);
			store.setIsValid(1l);
			storeService.saveStoreAndFile(store);
			log.info("添加商户, 商户编号：" + store.getId());
			logUtils.logAdd("商户管理", "添加广告商户, 商户编号：" + store.getId());
		} catch (Exception e) {
			log.error("新增商户失败", e);
			logUtils.logAdd("商户管理", "新增商户失败");
		}
		return JsonRespWrapper.success("操作成功", "/store/list");
	}

	/**
	 * 进入商户查看页面
	 * 
	 * @param id
	 *            商户编号
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/storeView/{id}")
	public String storeView(@PathVariable Long id, Model model) {
		Store store = this.storeService.findStoreById(id);
		try {
			List<AuditStep> auditStepList = this.storeService.findShopAuditSteplist(store.getId());
			model.addAttribute("auditStepList", auditStepList);
		} catch (Exception e) {
			log.error("查看商户信息失败，商户id：" + id, e);
		}
		SysRegion re = sysRegionService.findByRegionCode(store.getAreaCode());
		store.setAreaName(re.getRegionName());
		model.addAttribute("store", store);
		return "/store/store-view";
	}

	/**
	 * 进入商户修改页面
	 * 
	 * @param id
	 *            商户编号
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/storeEdit", method = RequestMethod.GET)
	public String storeEdit(@RequestParam Long id, Model model) {
		// 得到商户
		Store store = storeService.findStoreById(id);
		SysRegion region = this.sysRegonService.findByRegionCode(store.getAreaCode());
		if (region != null) {
			store.setAreaName(region.getRegionName());
		}
		model.addAttribute("store", store);
		model.addAttribute("uploadImgId", new Date().getTime());
		model.addAttribute("pid", SessionUser.getSessionUser().getSysUnit().getAreaCode());
		return "/store/store-edit";
	}

	/**
	 * 商户修改
	 * 
	 * @param uploadfile
	 *            合同文件
	 * @param store
	 *            商户
	 * @param model
	 * @param request
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/storeEdit", method = RequestMethod.POST)
	@ResponseBody
	public Object storeUpdate(Store store, Model model, HttpServletRequest request) {
		try {
			if (!RegUtils.onlyNumAndcCharacterAndAlphabet(store.getName())) {
				return JsonRespWrapper.successAlert("商户名不合法!");
			}
			Store oldstore = this.storeService.findStoreById(store.getId());
			String oldName = oldstore.getName();
			String newName = store.getName();
			if (!oldName.equals(newName)) {
				boolean exit = storeService.checkExit(store);
				if (!exit) {
					return JsonRespWrapper.successAlert("商户名已经存在!");
				}
			}
			storeService.updateStoreAndFile(store, oldstore);
			log.info("修改商户成功, 商户编号：" + store.getId());
			logUtils.logModify("商户管理", "修改商户成功, 商户编号：" + store.getId());
		} catch (Exception e) {
			log.error("修改商户失败，商户id：" + store.getId(), e);
			logUtils.logAdd("商户管理", "修改商户失败，商户id：" + store.getId());
		}
		// 返回到来源页面
		String backUrl = request.getParameter("backUrl");
		return JsonRespWrapper.success("修改成功", backUrl);
	}

	/**
	 * 送审
	 * 
	 * @param id
	 *            商户编号
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/audit/{id}")
	@ResponseBody
	public Object audit(@PathVariable Long id, Model model) {
		Store store = this.storeService.findStoreById(id);
		store.setStatus(1l);
		storeService.saveStore(store);
		log.info("商户送审, 商户编号：" + store.getId());
		logUtils.logAudit("商户管理", "商户送审, 商户编号：" + store.getId());
		return JsonRespWrapper.successReload("送审成功");

	}

	/**
	 * 获取待审核商户页面信息
	 * 
	 * @param store
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/auditList")
	public String auditList(@ModelAttribute("store") Store store, @RequestParam(value = "page", required = false, defaultValue = "1") int page, Model model) {
		try {
			Page<Store> storeList = storeService.listStore(store, page, Page.DEFAULT_PAGESIZE, "1,2", null);
			model.addAttribute("pageData", storeList);
		} catch (Exception e) {
			log.error("获取待审核商户页面信息出错", e);
		}
		model.addAttribute("statusMap", Store.statusMap);
		return "/store/store-audit-list";

	}

	/**
	 * 跳转到审核页面
	 * 
	 * @param id
	 *            商户编号
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/storeAudit", method = RequestMethod.GET)
	public String toAuditPage(@RequestParam(value = "id") Long id, Model model) {
		Store store = storeService.findStoreById(id);
		model.addAttribute("store", store);
		return "/store/store_auditing";
	}

	/**
	 * 审核商户
	 * 
	 * @param id
	 *            商户编号
	 * @param step
	 *            审核步骤
	 * @param status
	 *            审核状态
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/storeAudit", method = RequestMethod.POST)
	@ResponseBody
	public Object storeAudit(@RequestParam(value = "id") Long id, Long status, Model model) {
		Store store = this.storeService.findStoreById(id);
		store.setStatus(status);
		storeService.saveStore(store);
		logUtils.logAudit("商户管理", "商户审核, 商户编号：" + store.getId());
		return JsonRespWrapper.success("审核成功", "/store/auditList");
	}

	/**
	 * 删除商户
	 * 
	 * @param id
	 *            商户id
	 * @return
	 */
	@RequestMapping(value = "/storeDel/{id}")
	@ResponseBody
	public Object storeDel(@PathVariable(value = "id") Long id) {
		Store store = this.storeService.findStoreById(id);
		store.setIsValid(0l);
		this.storeService.saveStore(store);
		log.info("删除商户, 商户编号：" + store.getId());
		logUtils.logDelete("商户管理", "删除商户, 商户编号：" + store.getId());
		return JsonRespWrapper.success("删除成功", "/store/list");
	}

	/**
	 * 进入选择商户页面
	 * 
	 * @param store
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/selectStore", method = RequestMethod.GET)
	public String selectStores(Store store, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) {
		try {
			Page<Store> storePage = storeService.listStore(store, page, 15, null, null);
			model.addAttribute("pageData", storePage);
		} catch (Exception e) {
			log.error("进入选择商户页面失败", e);
		}
		// 跳转到列表页面
		return "store/select-store";
	}

	/**
	 * 进入选择商户多选页面（在用）
	 * 
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@RequestMapping(value = "/findStore", method = RequestMethod.GET)
	public String selectStores(Store store, @RequestParam(required = false) String ids, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) throws IOException, Exception {
		store.setIsValid(1L);

		if (ids != null && !"".equals(ids)) {
			if (ids.endsWith(",")) {
				ids = ids.substring(0, ids.lastIndexOf(","));
			}
			List<Store> rightStoreList = storeService.getStoreListByFilter(ids);
			model.addAttribute("rightStoreList", rightStoreList);
		}
		Page<Store> storePage = storeService.listStore(store, page, 15, null, ids);
		model.addAttribute("pageData", storePage);
		// 跳转到列表页面
		return "store/select-storelist";
	}

	/**
	 * Ajax商户查询（在用）
	 * 
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@RequestMapping(value = "/selectAjaxStore")
	@ResponseBody
	public Object findStoreAjax(Store store, @RequestParam(required = false) String ids, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) throws IOException, Exception {
		store.setIsValid(1L);
		Page<Store> storePage = storeService.listStore(store, page, 15, null, "");
		return storePage;
	}

	/**
	 * @Title: 关联后台用户弹框 <br>
	 * @param model
	 * @return
	 * @throws
	 */
	@RequestMapping(value="/selectSysUser")
	public String selectSysUser(HttpSession session, SysUser sysUser, @RequestParam(required = false, value = "page", defaultValue = "1") int page, Model model) {
		Page<SysUser> userlist = null;
		try {
			userlist = userService.listUserNotLink(sysUser, session, page);
		} catch (SQLException e) {
			log.error("查询后台用户异常:" + e.getMessage());
		}
		model.addAttribute("pageData", userlist);
		model.addAttribute("sysUser", sysUser);
		return "store/select-user-list";
	}
	
	/**
	 * Ajax商户关联后台用户
	 * 
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@RequestMapping(value = "/ajaxLinkSysUser")
	@ResponseBody
	public Object linkSysUserAjax(@RequestParam Long id, @RequestParam Long userId) throws IOException, Exception {
		try{
			Store store = storeService.findStoreById(id);
			SysUser sysUser = userService.findSysUserById(userId);
			if (store != null && sysUser != null) {
				store.setSysUserId(userId);
				storeService.saveStore(store);
			}
		} catch (Exception e) {
			log.error("商户关联后台帐号异常:"+e.getMessage());
			return JsonRespWrapper.error("关联失败!");
		}
		logUtils.logAdd("商户管理", "关联后台帐号成功");
		return JsonRespWrapper.successReload("关联成功!");
	}

}
